<template>
  <div class="qr-code">
    <canvas ref="canvas" :style="{ width: this.width, height: this.width }" />
  </div>
</template>

<script>
import * as QRCode from 'qrcode';

export default {
  name: 'QrCode',
  props: {
    value: {
      type: String,
      default: ''
    },
    width: {
      type: Number,
      default: 100
    }
  },
  watch: {
    value: {
      handler(nv) {
        this.generateQRCode(nv);
      },
      immediate: true
    },
    width: {
      handler(nv) {
        this.generateQRCode(this.value);
      }
    }
  },
  methods: {
    generateQRCode(text) {
      if (text == null || text === '') {
        console.warn('No text provided for QR Code generation.');
        return;
      }
      if (this.$refs.canvas) {
        QRCode.toCanvas(
          this.$refs.canvas,
          text,
          { errorCorrectionLevel: 'H', width: this.width, height: this.width },
          error => {
            if (error) console.error(error);
            console.log('QR Code generated successfully!');
          }
        );
      }
    }
  },
  mounted() {
    this.generateQRCode(this.value);
  }
};
</script>
